﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;

//Declarations

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataSet ds;

        public Form1()
        {
            InitializeComponent();
            txtPreparedBy.Text = "Robert Brown";
            txtDate.Text = DateTime.Today.ToString();

            ds = new DataSet("QM");
            DataTable characteristics = ds.Tables.Add("Characteristics");
 
            //build table
            characteristics.Columns.AddRange(new DataColumn[] {  
            new DataColumn("CharNo", typeof(string)),  
            new DataColumn("RefLoc", typeof(string)),  
            new DataColumn("CharType", typeof(string)),  
            new DataColumn("CharDesig", typeof(string)), 
            new DataColumn("Min", typeof(string)),
            new DataColumn("Req", typeof(string)), 
            new DataColumn("Max", typeof(string)),
            new DataColumn("Results", typeof(string)), 
            new DataColumn("DesTool", typeof(string)), 
            new DataColumn("NCNumber", typeof(string)), 

  
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FormatGrid();
        }
        private void FormatGrid()
        {
            try
            {
                dataGridView1.Columns["CharNo"].HeaderText = "5. Char No.";
                dataGridView1.Columns["CharNo"].Width = 50;
                dataGridView1.Columns["RefLoc"].HeaderText = "6. Reference Location";
                dataGridView1.Columns["RefLoc"].Width = 100;
                dataGridView1.Columns["CharType"].HeaderText = "7a. CharacteristicType";
                dataGridView1.Columns["CharType"].Width = 150;
                dataGridView1.Columns["CharDesig"].HeaderText = "7b. Characteristic Designator";
                dataGridView1.Columns["CharDesig"].Width = 100;
                dataGridView1.Columns["Min"].HeaderText = "8a. MinValue";
                dataGridView1.Columns["Req"].HeaderText = "8b. TargetValue";
                dataGridView1.Columns["Max"].HeaderText = "8c. MaxValue";
                dataGridView1.Columns["Results"].HeaderText = "9. Results";
                dataGridView1.Columns["DesTool"].HeaderText = "10. Designed Tooling";
                dataGridView1.Columns["NCNumber"].HeaderText = "11. Non-Conformance Number";
            }
            catch { }


        }

        private void btnQMPlan_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "XML files |*.xml";
            saveFileDialog1.InitialDirectory = "C:\\QMP\\schemas\\QIFWorkingFiles2012July8\\QIFWorkingFiles2012July8\\sampleDataFiles\\";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
               
                using (XmlTextWriter writer = new XmlTextWriter(saveFileDialog1.FileName.ToString(), null))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 5;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("MeasurementPlan"); //root
                    writer.WriteAttributeString("id", "SampleQMPlan");
                    writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    writer.WriteAttributeString("xsi:noNamespaceSchemaLocation", "../applications/QMPlans.xsd");

                    //File Units Section - question necessity since unitName is an attribute in the CharacteristicNominal section
                    writer.WriteStartElement("FileUnits"); //Unit section
                    writer.WriteStartElement("PrimaryUnits");
                    writer.WriteStartElement("AngleUnit");
                    writer.WriteElementString("SIUnitName", "radian");
                    writer.WriteElementString("UnitName", "degree");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.017453293");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteStartElement("LengthUnit");
                    writer.WriteElementString("SIUnitName", "meter");
                    writer.WriteElementString("UnitName", "inch");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.017453293");
                    writer.WriteElementString("Offset", "0");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteStartElement("TemperatureUnit");
                    writer.WriteElementString("SIUnitName", "kelvin");
                    writer.WriteElementString("UnitName", "Fahrenheit");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.555555556");
                    writer.WriteElementString("Offset", "459.67");

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    // End of File Units section
                    //************************************************************************************************
                    // Begin Traceabilty section
                    writer.WriteStartElement("Traceabilities");
                    writer.WriteStartElement("Traceability");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("SampleNumber", txtSerialNumber.Text);
                    writer.WriteElementString("PartInstanceId", "1");
                    writer.WriteElementString("ReportNumber", txtFAIReportNumber.Text);
                    writer.WriteStartElement("ReportPreparer");
                    writer.WriteElementString("Name", txtPreparedBy.Text);
                    writer.WriteElementString("EmployeeId", "1");
                    writer.WriteEndElement();
                    writer.WriteElementString("ReportPreparationDate", txtDate.Text);
                    //MeasurementDeviceIds section optional but requires references if used
                    //writer.WriteStartElement("MeasurementDeviceIds");
                    //writer.WriteStartElement("MeasurementDeviceId");
                    //writer.WriteElementString("Id", "CMM_1");
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    writer.WriteStartElement("StandardAndVersion", "");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    //End Traceability section
                    //****************************************************************************************************
                    //Non AS9102 sections

                    //Sampling Plans - optional
                    writer.WriteStartElement("QualityControlPlan");
                    writer.WriteStartElement("Sampling");
                    writer.WriteStartElement("SamplingPlans");
                    writer.WriteStartElement("SamplingPlan");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("SampleSize", "1");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteElementString("MeasurementCycleTime", "P1D");
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //Part Models    - Optional
                    writer.WriteStartElement("PartModels");
                    writer.WriteStartElement("PartGeometryDefinition");

                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartId", "1");
                    writer.WriteStartElement("DigitalPartDrawing");

                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("FileName", "");
                    writer.WriteElementString("Format", "");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    //Parts
                    writer.WriteStartElement("Parts");
                    writer.WriteStartElement("PartDefinitions");
                    writer.WriteStartElement("PartDefinition");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartName", txtPartNumber.Text);
                    writer.WriteElementString("PartModelNumber", txtPartNumber.Text);
                    writer.WriteStartElement("FeatureAspects");

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //Part Instances

                    writer.WriteStartElement("PartInstances");
                    writer.WriteStartElement("PartInstance");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartDefinitionId", "1");
                    writer.WriteElementString("Status", "UNKNOWN");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //**************************************************************************************************************
                    //Start Characteristics section
                    writer.WriteStartElement("Characteristics");

                    writer.WriteStartElement("CharacteristicDefinitions");
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        //Grid
                        if (row.Cells["CharNo"].Value != null) //avoid new row 
                        {
                            writer.WriteStartElement("UserDefinedVariableCharacteristicDefinition"); //repeating rows
                            writer.WriteAttributeString("id", row.Cells["RefLoc"].Value.ToString()); //use of XML attribute
                            writer.WriteElementString("Name", row.Cells["CharDesig"].Value.ToString());
                            writer.WriteEndElement();
                        }

                    }
                    writer.WriteEndElement();

                    writer.WriteStartElement("CharacteristicNominals");
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        //Grid
                        if (row.Cells["CharNo"].Value != null) //avoid new row 
                        {
                            writer.WriteStartElement("UserDefinedVariableCharacteristicNominal"); //repeating rows
                            writer.WriteAttributeString("id", row.Cells["CharNo"].Value.ToString()); //use of XML attribute
                            writer.WriteElementString("Name", row.Cells["RefLoc"].Value.ToString());
                            writer.WriteElementString("Description", row.Cells["CharDesig"].Value.ToString());
                            writer.WriteElementString("DefinitionId", row.Cells["RefLoc"].Value.ToString());
                            writer.WriteStartElement("TargetValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Req"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteStartElement("MaxValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Max"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteStartElement("MinValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Min"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteElementString("DefinedAsLimit", "true");//Requirement
                            writer.WriteEndElement();
                        }

                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //Plan section
                    writer.WriteStartElement("UnorderedPlanRoot");
                    writer.WriteStartElement("Steps");
                    writer.WriteStartElement("MeasureEvaluateAll");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //End 
                    writer.WriteEndDocument();
                    FormatGrid();
                }
            }
        }
        private void btnQMPlanRead_Click(object sender, EventArgs e)
        {

            //load file
            OpenFileDialog fDialog = new OpenFileDialog();
            fDialog.Title = "Open QMPlan File";
            fDialog.Filter = "XML Files|*.xml";
            fDialog.InitialDirectory = "C:\\QMP\\schemas\\QIFWorkingFiles2012July8\\QIFWorkingFiles2012July8\\sampleDataFiles\\";
            if (fDialog.ShowDialog() == DialogResult.OK)
            {

                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(fDialog.FileName.ToString());

                //header and footer
                txtPartNumber.Text = xmlDoc.SelectSingleNode("//Parts/PartDefinitions/PartDefinition/PartModelNumber").InnerText;//PartNumber
                txtPartName.Text = xmlDoc.SelectSingleNode("//Parts/PartDefinitions/PartDefinition/PartName").InnerText;//PartName
                txtSerialNumber.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/SampleNumber").InnerText;//SerialNumber
                txtFAIReportNumber.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportNumber").InnerText;//FAIReportNumber
                txtPreparedBy.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportPreparer/Name").InnerText;//PreparedBy
                txtDate.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportPreparationDate").InnerText;//Date


                //grid
                DataTable characteristics = ds.Tables["Characteristics"];
                characteristics.Clear();
                int i = 0;
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("DiameterCharacteristicDefinition"))
                    try
                    {
                        //get nominal id
                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/DiameterCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string limit = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/DefinedAsLimit").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/DiameterCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                       
                        if (limit == "false")
                        {
                            double targetint = double.Parse(target);
                            double maxint = double.Parse(max);
                            double minint = double.Parse(min);
                            min = (targetint + minint).ToString();
                            max = (targetint + maxint).ToString();
                        }
                        {
                            DataRow row = characteristics.Rows.Add(i,
                                charNode.Attributes["id"].Value,//Reference Location
                                "DiameterCharacterisitc",
                                charNode["Name"].InnerText,//CharacteristicDesignator
                                min,
                                target,
                                max,
                                "N/A",//charNode["Results"].InnerText,
                                "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                                "NCNumber"); //charNode["NCNumber"].InnerText);
                            i = i + 1;
                        }
                    }
                    catch
                    {
                    }
                try
                {
                    foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("LinearCharacteristicDefinition"))
                    {
                        DataRow row = characteristics.Rows.Add(i,
                            charNode.Attributes["id"].Value,//Reference Location
                            "LinearCharacterisitic",
                            charNode["Name"].InnerText,//CharacteristicDesignator
                            xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/LinearCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText,
                            xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/LinearCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText,
                            xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/LinearCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText,
                            "N/A",//charNode["Results"].InnerText,
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;

                    }
                }
                catch
                {
                }
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("CoordinateCharacteristicDefinition"))
                {
                    try
                    {

                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/CoordinateCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/CoordinateCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                        string limit = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/DefinedAsLimit").InnerText;
                        if (limit == "false")
                        {
                            double targetint = double.Parse(target);
                            double maxint = double.Parse(max);
                            double minint = double.Parse(min);
                            min = (targetint + minint).ToString();
                            max = (targetint + maxint).ToString();
                        }
                        DataRow row = characteristics.Rows.Add(i,
                            //charNode["NominalId"].InnerText,//Reference Location
                            charNode.Attributes["id"].Value,
                            "CoordinateCharacteristic",
                            charNode["Name"].InnerText,//CharacteristicDesignator
                            min,
                            target,
                            max,
                            "N/A",
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;
                    }
                    catch
                    {

                    }



                }
                try
                {
                    foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("UserDefinedVariableCharacteristicNominal"))
                    {
                        DataRow row = characteristics.Rows.Add(i,
                            charNode["Name"].InnerText,//Reference Location
                            "UserDefinedCharacteristic",
                            charNode["Description"].InnerText,//CharacteristicDesignator
                            charNode["MinValue"].InnerText,//Requirement
                            charNode["TargetValue"].InnerText,//Requirement
                            charNode["MaxValue"].InnerText,//Requirement
                            "N/A",//charNode["Results"].InnerText,
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;

                    }
                }
                catch
                {
                }

                characteristics.AcceptChanges();
                dataGridView1.Columns.Clear();
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = ds.Tables["Characteristics"];
            }
            FormatGrid();
        }
        private void button3_Click(object sender, EventArgs e)
        {
                     //load file
         XmlDocument xmlDoc = new XmlDocument ();


            OpenFileDialog fDialog = new OpenFileDialog();
            fDialog.Title = "Open QMResult File";
            fDialog.Filter = "XML Files|*.xml";
            fDialog.InitialDirectory = "C:\\QMP\\schemas\\QIFWorkingFiles2012July8\\QIFWorkingFiles2012July8\\sampleDataFiles\\";
            if (fDialog.ShowDialog() == DialogResult.OK)
            {
                xmlDoc.Load(fDialog.FileName.ToString());
                //header and footer
                txtPartNumber.Text = xmlDoc.SelectSingleNode("//Parts/PartDefinitions/PartDefinition/PartModelNumber").InnerText;//PartNumber
                txtPartName.Text = xmlDoc.SelectSingleNode("//Parts/PartDefinitions/PartDefinition/PartName").InnerText;//PartName
                txtSerialNumber.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/SampleNumber").InnerText;//SerialNumber
                txtFAIReportNumber.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportNumber").InnerText;//FAIReportNumber
                txtPreparedBy.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportPreparer/Name").InnerText;//PreparedBy
                txtDate.Text = xmlDoc.SelectSingleNode("//Traceabilities/Traceability/ReportPreparationDate").InnerText;//Date

                //grid
                DataTable characteristics = ds.Tables["Characteristics"];
                characteristics.Clear();
                int i = 0;
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("DiameterCharacteristicDefinition"))
                {
                    try
                    {
                        //get nominal id
                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/DiameterCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string limit = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/DefinedAsLimit").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/DiameterCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/DiameterCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                        string actual = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicActuals/DiameterCharacteristicActual[NominalId[.='" + nominal + "']]/Value/ActualValue/Lval").InnerText;
                        if (limit == "false")
                        {
                            double targetint= double.Parse(target);
                            double maxint=double.Parse(max);
                            double minint=double.Parse(min);
                            min = (targetint + minint).ToString();
                            max = (targetint + maxint).ToString();
                        }
                        
                        //get tolerances, nominal and actual
                        DataRow row = characteristics.Rows.Add(i,
                           charNode.Attributes["id"].Value,//Reference Location
                           "DiameterCharacteristic",
                           charNode["Name"].InnerText,//CharacteristicDesignator
                            min,
                            target,
                            max,
                            actual,
                           "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                           "NCNumber"); //charNode["NCNumber"].InnerText);

                        i = i + 1;
                    }
                    catch
                    {
                    }
                }
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("LinearCharacteristicDefinition"))
                {
                    try
                    {
                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/LinearCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/LinearrCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string limit = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/LinearCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/DefinedAsLimit").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/LinearCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/LinearCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                        string actual = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicActuals/LinearCharacteristicActual[NominalId[.='" + nominal + "']]/Value/ActualValue/Lval").InnerText;
                        if (limit == "false")
                        {
                            double targetint = double.Parse(target);
                            double maxint = double.Parse(max);
                            double minint = double.Parse(min);
                            min = (targetint + minint).ToString();
                            max = (targetint + maxint).ToString();
                        }
                        DataRow row = characteristics.Rows.Add(i,
                            charNode.Attributes["id"].Value, //Reference Location
                            "LinearCharacteristic",
                            charNode["Name"].InnerText,//CharacteristicDesignator
                            min,
                            target,
                            max,
                            //charNode["TargetValue"].InnerText,//Requirement
                            actual,
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;
                    }
                    catch
                    {
                    }

                }
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("CoordinateCharacteristicDefinition"))
                {
                    try
                    {

                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/CoordinateCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string limit = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/DefinedAsLimit").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/CoordinateCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/CoordinateCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                        string actual = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicActuals/CoordinateCharacteristicActual[NominalId[.='" + nominal + "']]/Value/ActualValue/Lval").InnerText;

                        if (limit == "false")
                        {
                            double targetint = double.Parse(target);
                            double maxint = double.Parse(max);
                            double minint = double.Parse(min);
                            min = (targetint + minint).ToString();
                            max = (targetint + maxint).ToString();
                        }
                        
                        DataRow row = characteristics.Rows.Add(i,
                            charNode.Attributes["id"].Value, //Reference Location
                            "CoordinateCharacteristic",
                            charNode["Name"].InnerText,//CharacteristicDesignator
                            min,
                            target,
                            max,
                            actual,
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;
                    }
                    catch
                    {

                    }



                }
                foreach (XmlNode charNode in xmlDoc.GetElementsByTagName("PointProfileCharacteristicDefinition"))
                {
                    try
                    {

                        string nominal = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/PointProfileCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]").Attributes["id"].Value;
                        string min = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/PointProfileCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MinValue/Lval").InnerText;
                        string max = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicDefinitions/PointProfileCharacteristicDefinition[@id='" + charNode.Attributes["id"].Value + "']/Tolerance/MaxValue/Lval").InnerText;
                        string target = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicNominals/PointProfileCharacteristicNominal[DefinitionId[.='" + charNode.Attributes["id"].Value + "']]/TargetValue").InnerText;
                        string actual = xmlDoc.SelectSingleNode("//Characteristics/CharacteristicActuals/PointProfileCharacteristicActual[NominalId[.='" + nominal + "']]/Value/ActualValue/Lval").InnerText;

                        DataRow row = characteristics.Rows.Add(i,

                            charNode.Attributes["id"].Value, //Reference Location
                            "ProfileCharacteristic",
                            charNode["Name"].InnerText,//CharacteristicDesignator
                            min,
                            target,
                            actual,
                            "DesignatedTool",//charNode["DesignatedTool"].InnerText,
                            "NCNumber"); //charNode["NCNumber"].InnerText);
                        i = i + 1;
                    }
                    catch
                    {

                    }



                }

                characteristics.AcceptChanges();
                dataGridView1.Columns.Clear();
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = ds.Tables["Characteristics"];
                FormatGrid();

                //conformance judgement
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["CharNo"].Value != null)
                    {
                        if ((double.Parse(row.Cells["Results"].Value.ToString()) > double.Parse(row.Cells["Min"].Value.ToString())) && (double.Parse(row.Cells["Results"].Value.ToString()) < double.Parse(row.Cells["Max"].Value.ToString())))
                        {
                            row.Cells[7].Style.ForeColor = Color.Green;
                        }
                        else
                        {
                            row.Cells[7].Style.ForeColor = Color.Red;
                        }
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "XML files |*.xml";
            saveFileDialog1.InitialDirectory = "C:\\QMP\\schemas\\QIFWorkingFiles2012July8\\QIFWorkingFiles2012July8\\sampleDataFiles\\";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                using (XmlTextWriter writer = new XmlTextWriter(saveFileDialog1.FileName.ToString(), null))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 5;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Inspection"); //root
                    writer.WriteAttributeString("id", "SampleQMResult");
                    writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    writer.WriteAttributeString("xsi:noNamespaceSchemaLocation", "../applications/QMResults.xsd");

                    //File Units Section - question necessity since unitName is an attribute in the CharacteristicNominal section
                    writer.WriteStartElement("MeasurementResults");
                    writer.WriteStartElement("Settings");
                    writer.WriteStartElement("FileUnits"); //Unit section
                    writer.WriteStartElement("PrimaryUnits");
                    writer.WriteStartElement("AngleUnit");
                    writer.WriteElementString("SIUnitName", "radian");
                    writer.WriteElementString("UnitName", "degree");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.017453293");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteStartElement("LengthUnit");
                    writer.WriteElementString("SIUnitName", "meter");
                    writer.WriteElementString("UnitName", "inch");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.017453293");
                    writer.WriteElementString("Offset", "0");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteStartElement("TemperatureUnit");
                    writer.WriteElementString("SIUnitName", "kelvin");
                    writer.WriteElementString("UnitName", "Fahrenheit");
                    writer.WriteStartElement("UnitConversion");
                    writer.WriteElementString("Factor", "0.555555556");
                    writer.WriteElementString("Offset", "459.67");

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    // End of File Units section
                    //************************************************************************************************
                    // Begin Traceabilty section
                    writer.WriteStartElement("Traceabilities");
                    writer.WriteStartElement("Traceability");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("SampleNumber", txtSerialNumber.Text);
                    writer.WriteElementString("PartInstanceId", "1");
                    writer.WriteElementString("ReportNumber", txtFAIReportNumber.Text);
                    writer.WriteStartElement("ReportPreparer");
                    writer.WriteElementString("Name", txtPreparedBy.Text);
                    writer.WriteElementString("EmployeeId", "1");
                    writer.WriteEndElement();
                    writer.WriteElementString("ReportPreparationDate", txtDate.Text);
                    //MeasurementDeviceIds section optional but requires references if used
                    //writer.WriteStartElement("MeasurementDeviceIds");
                    //writer.WriteStartElement("MeasurementDeviceId");
                    //writer.WriteElementString("Id", "CMM_1");
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    writer.WriteStartElement("StandardAndVersion", "");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    //End Traceability section
                    //****************************************************************************************************
                    //Non AS9102 sections


                    //Part Models    - Optional
                    writer.WriteStartElement("PartModels");
                    writer.WriteStartElement("PartGeometryDefinition");

                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartId", "1");
                    writer.WriteStartElement("DigitalPartDrawing");

                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("FileName", "");
                    writer.WriteElementString("Format", "");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    //Parts
                    writer.WriteStartElement("Parts");
                    writer.WriteStartElement("PartDefinitions");
                    writer.WriteStartElement("PartDefinition");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartName", txtPartNumber.Text);
                    writer.WriteElementString("PartModelNumber", txtPartNumber.Text);
                    writer.WriteStartElement("FeatureAspects");

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //Part Instances

                    writer.WriteStartElement("PartInstances");
                    writer.WriteStartElement("PartInstance");
                    writer.WriteAttributeString("id", "1");
                    writer.WriteElementString("PartDefinitionId", "1");
                    //Required making FeatureInstances and CharacteristicFeatureRelations optional in the schema to validate output
                    //writer.WriteStartElement("FeatureInstances");
                    //writer.WriteStartElement("CylinderFeatureInstance");
                    //writer.WriteAttributeString("id", "1");
                    //writer.WriteAttributeString("materialDirection", "INNER");
                    //writer.WriteElementString("PartDefinitionId", txtPartNumber.Text);
                    //writer.WriteElementString("FeatureNominalId", "1");
                    //writer.WriteElementString("FeatureName", txtPartNumber.Text);
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    writer.WriteElementString("Status", "UNKNOWN");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();

                    //**************************************************************************************************************
                    //Start Characteristics section
                    writer.WriteStartElement("Characteristics");

                    writer.WriteStartElement("CharacteristicDefinitions");
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        //Grid
                        if (row.Cells["CharNo"].Value != null) //avoid new row 
                        {
                            writer.WriteStartElement("UserDefinedVariableCharacteristicDefinition"); //repeating rows
                            writer.WriteAttributeString("id", row.Cells["RefLoc"].Value.ToString()); //use of XML attribute
                            writer.WriteElementString("Name", row.Cells["CharDesig"].Value.ToString());
                            writer.WriteEndElement();
                        }

                    }
                    writer.WriteEndElement();

                    writer.WriteStartElement("CharacteristicNominals");
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        //Grid
                        if (row.Cells["CharNo"].Value != null) //avoid new row 
                        {
                            writer.WriteStartElement("UserDefinedVariableCharacteristicNominal"); //repeating rows
                            writer.WriteAttributeString("id", row.Cells["CharNo"].Value.ToString()); //use of XML attribute
                            writer.WriteElementString("Name", row.Cells["RefLoc"].Value.ToString());
                            writer.WriteElementString("Description", row.Cells["CharDesig"].Value.ToString());
                            writer.WriteElementString("DefinitionId", row.Cells["RefLoc"].Value.ToString());
                            writer.WriteStartElement("TargetValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Req"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteStartElement("MaxValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Max"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteStartElement("MinValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Min"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                            writer.WriteElementString("DefinedAsLimit", "true");//Requirement
                            writer.WriteEndElement();
                        }

                    }
                    writer.WriteEndElement();
                    writer.WriteStartElement("CharacteristicActuals");
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        //Grid
                        if (row.Cells["CharNo"].Value != null) //avoid new row 
                        {
                            writer.WriteStartElement("UserDefinedVariableCharacteristicActual"); //repeating rows
                            writer.WriteAttributeString("id", row.Cells["CharNo"].Value.ToString()); //use of XML attribute
                            writer.WriteElementString("Name", row.Cells["CharDesig"].Value.ToString());
                            writer.WriteElementString("Status", "NOT_ANALYZED");
                            writer.WriteElementString("NominalId", row.Cells["CharNo"].Value.ToString());
                            writer.WriteStartElement("ActualValue");
                            writer.WriteAttributeString("unitName", "inch");
                            writer.WriteString(row.Cells["Results"].Value.ToString());//Requirement
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }


                    writer.WriteEndElement();
                    writer.WriteStartElement("InspectionStatus");
                    writer.WriteElementString("Status", "NOT_CALCULATED");
                    writer.WriteEndElement();

                    //End 
                    writer.WriteEndElement();
                    writer.WriteElementString("Version", "1");
                    writer.WriteEndDocument();
                    FormatGrid();
                }
            }
        }

    }
}
